package com.aluka.nirvana.framework.core.exception;

import com.google.common.base.MoreObjects;
import com.google.common.base.Strings;
import lombok.Getter;
import lombok.Setter;

/**
 * 业务异常基类
 * @author gongli
 * @since 2019/12/25
 */
public abstract class BaseException extends RuntimeException {

    private static final long serialVersionUID = 4773191322243855500L;
    @Getter
    private final String errorCode;
    @Getter
    @Setter
    private String additionalMessage;

    public <T extends Enum<T> & ErrorEnumInterface> BaseException(T errorEnum) {
        this(errorEnum, "");
    }

    public <T extends Enum<T> & ErrorEnumInterface> BaseException(T errorEnum, String message) {
        this(errorEnum, message, null);
    }
    public <T extends Enum<T> & ErrorEnumInterface> BaseException(T errorEnum, Throwable cause) {
        this(errorEnum, "", cause);
    }
    public <T extends Enum<T> & ErrorEnumInterface> BaseException(T errorEnum, String message, Throwable cause) {
        super(errorEnum.getErrorInfo().getMessage() + (Strings.isNullOrEmpty(message) ? "" : ":" + message) + (cause == null ? "" : "[" + cause.getMessage() + "]"), cause);
        ErrorInfo errorInfo = errorEnum.getErrorInfo();
        this.errorCode = errorInfo.getCode();
    }
    public <T extends Enum<T> & ErrorEnumInterface> BaseException(String errorCode, String message, Throwable cause) {
        super(message + (cause == null ? "" : "[" + cause.getMessage() + "]"), cause);
        this.errorCode = errorCode;
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
                .add("message", this.getMessage())
                .add("code", this.errorCode)
                .add("additionalMessage", this.additionalMessage)
                .toString();
    }
}
